<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
			<el-form-item label="工器具编号" prop="materialCode">
				<el-input v-model="queryParams.materialCode" placeholder="请输入工器具编号" clearable @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="工器具名称" prop="materialName">
				<el-input v-model="queryParams.materialName" placeholder="请输入工器具名称" clearable @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="状态" prop="materialStatus">
				<el-select v-model="queryParams.materialStatus" placeholder="请选择状态" clearable>
					<el-option v-for="dict in dict.type.material_status" :key="dict.value" :label="dict.label" :value="dict.value" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['elec:elecMaterialSg:add']">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['elec:elecMaterialSg:edit']">修改</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
				 v-hasPermi="['elec:elecMaterialSg:remove']">删除</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['elec:elecMaterialSg:import']">导入</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['elec:elecMaterialSg:export']">导出</el-button>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table v-loading="loading" :data="elecMaterialList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="主键ID" align="center" prop="materialId" />
			<el-table-column label="工器具编号" align="center" prop="materialCode" width="100" />
			<el-table-column label="工器具名称" align="center" prop="materialName" width="200" />
			<el-table-column label="状态" align="center" prop="materialStatus">
				<template slot-scope="scope">
					<dict-tag :options="dict.type.material_status" :value="scope.row.materialStatus" />
				</template>
			</el-table-column>
			<el-table-column label="规格型号" align="center" prop="specifications" width="100" />
			<el-table-column label="分类" align="center" prop="sortName" width="100" />
			<el-table-column label="库房" align="center" prop="warehouseName" width="100" />
			<el-table-column label="柜架" align="center" prop="cabinetName" width="100" />
			<el-table-column label="层位" align="center" prop="gridName" width="100" />
			<el-table-column label="单位" align="center" prop="unitName" />
			<el-table-column label="供应商" align="center" prop="providerName" width="100" />
			<el-table-column label="采购日期" align="center" prop="purchaseDate" width="180">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.purchaseDate, '{y}-{m}-{d}') }}</span>
				</template>
			</el-table-column>
			<el-table-column label="入库日期" align="center" prop="inDate" width="180">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.inDate, '{y}-{m}-{d}') }}</span>
				</template>
			</el-table-column>
			<el-table-column label="检修周期" align="center" prop="repairCycle" />
			<el-table-column label="rfid编号" align="center" prop="rfidCode" width="200" />
			<el-table-column label="备注" align="center" prop="remark" width="200" />
			<el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width" fixed="right">
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['elec:elecMaterialSg:edit']">修改</el-button>
					<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['elec:elecMaterialSg:remove']">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
		 @pagination="getList" />

		<!-- 添加或修改工器具对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
			<el-form ref="form" :model="form" :rules="rules" label-width="100px">
				<el-row>
					<el-col :span="8">
						<el-form-item label="库房" prop="warehouseId">
							<el-select v-model="form.warehouseId" filterable placeholder="请选择库房" :disabled="disabled" @change="changeWarehouse">
								<el-option v-for="item in warehouseOptions" :key="item.value" :label="item.label" :value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="柜架" prop="cabinetId">
							<el-select v-model="form.cabinetId" filterable placeholder="请选择柜架" :disabled="disabled" @change="changeCabinet">
								<el-option v-for="item in cabinetOptions" :key="item.value" :label="item.label" :value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="层格" prop="gridId">
							<treeselect v-model="form.gridId" :options="gridOptions" :normalizer="normalizerGrid" :disabled="disabled" placeholder="选择层格"
							 noOptionsText="暂无数据" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="8">
						<el-form-item label="供应商" prop="providerId">
							<el-select v-model="form.providerId" filterable placeholder="请选择供应商">
								<el-option v-for="item in providerOptions" :key="item.value" :label="item.label" :value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="计量单位" prop="unitId">
							<el-select v-model="form.unitId" filterable placeholder="请选择计量单位">
								<el-option v-for="item in unitOptions" :key="item.value" :label="item.label" :value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="采购日期" prop="purchaseDate">
							<el-date-picker clearable v-model="form.purchaseDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择采购日期">
							</el-date-picker>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="工器具编号" prop="materialCode">
							<el-input v-model="form.materialCode" placeholder="请输入工器具编号" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="工器具名称" prop="materialName">
							<el-input v-model="form.materialName" placeholder="请输入工器具名称" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="分类" prop="sortId">
							<treeselect v-model="form.sortId" :options="sortOptions" :normalizer="normalizer" placeholder="选择分类"
							 noOptionsText="暂无数据" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="规格型号" prop="specifications">
							<el-input v-model="form.specifications" placeholder="请输入规格型号" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="检修周期/月" prop="repairCycle">
							<el-input-number v-model="form.repairCycle" placeholder="请输入检修周期" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="rfid编号" prop="rfidCode">
							<el-input v-model="form.rfidCode" placeholder="请输入rfid编号" />
						</el-form-item>
					</el-col>
				</el-row>

				<el-form-item label="备注" prop="remark">
					<el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
		<!-- 工器具导入对话框 -->
		<el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
			<el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport"
			 :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false"
			 drag>
				<i class="el-icon-upload"></i>
				<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
				<div class="el-upload__tip text-center" slot="tip">
					<div class="el-upload__tip" slot="tip">
						<el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的工器具数据
					</div>
					<span>仅允许导入xls、xlsx格式文件。</span>
					<el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
				</div>
			</el-upload>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitFileForm">确 定</el-button>
				<el-button @click="upload.open = false">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import {
		listElecMaterial,
		getElecMaterial,
		delElecMaterial,
		addElecMaterial,
		updateElecMaterial,
		listWarehouseOptions,
		listSortOptions,
		listCabinetOptions,
		listBasGridOptions,
		listProviderOptions,
		listUnitOptions
	} from "@/api/elec/elecMaterial";
	import {
		getToken
	} from "@/utils/auth";
	import Treeselect from "@riophae/vue-treeselect";
	import "@riophae/vue-treeselect/dist/vue-treeselect.css";

	export default {
		name: "ElecMaterial",
		dicts: ['material_status', 'spare_part_type'],
		components: {
			Treeselect
		},
		data() {
			return {
				// 遮罩层
				loading: true,
				// 选中数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 显示搜索条件
				showSearch: true,
				// 总条数
				total: 0,
				// 工器具表格数据
				elecMaterialList: [],
				// 弹出层标题
				title: "",
				// 是否显示弹出层
				open: false,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					materialCategory: '2',
					materialCode: null,
					materialName: null,
					materialStatus: null,
					sortId: null,
					warehouseId: null,
					providerId: null,
				},
				// 查询参数
				queryCabinetParams: {
					warehouseId: null,
				},
				// 查询参数
				queryGridParams: {
					cabinetId: null,
				},
				// 工器具导入参数
				upload: {
					// 是否显示弹出层（工器具导入）
					open: false,
					// 弹出层标题（工器具导入）
					title: "",
					// 是否禁用上传
					isUploading: false,
					// 是否更新已经存在的工器具数据
					updateSupport: 0,
					materialCategory: '2',
					// 设置上传的请求头部
					headers: {
						Authorization: "Bearer " + getToken()
					},
					// 上传的地址
					url: process.env.VUE_APP_BASE_API + "/elec/elecMaterial/importData"
				},
				// 表单参数
				form: {},
				// 表单校验
				rules: {
					materialCode: [{
						required: true,
						message: "工器具编号不能为空",
						trigger: "blur"
					}],
					materialName: [{
						required: true,
						message: "工器具名称不能为空",
						trigger: "blur"
					}],
					sortId: [{
						required: true,
						message: "分类不能为空",
						trigger: "change"
					}],
					warehouseId: [{
						required: true,
						message: "库房不能为空",
						trigger: "change"
					}],
					cabinetId: [{
						required: true,
						message: "柜架不能为空",
						trigger: "change"
					}],
					gridId: [{
						required: true,
						message: "层格不能为空",
						trigger: "change"
					}],
				},
				warehouseOptions: [],
				// 分类树选项
				sortOptions: [],
				cabinetOptions: [],
				gridOptions: [],
				providerOptions: [],
				unitOptions: [],
				disabled: false,
			};
		},
		created() {
			this.getList();
		},
		methods: {
			/** 查询工器具列表 */
			getList() {
				this.loading = true;
				listElecMaterial(this.queryParams).then(response => {
					this.elecMaterialList = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			// 取消按钮
			cancel() {
				this.open = false;
				this.reset();
			},
			/** 转换分类数据结构 */
			normalizer(node) {
				if (node.children && !node.children.length) {
					delete node.children;
				}
				return {
					id: node.sortId,
					label: node.sortName,
					children: node.children
				};
			},
			/** 转换层格数据结构 */
			normalizerGrid(node) {
				if (node.children && !node.children.length) {
					delete node.children;
				}
				return {
					id: node.gridId,
					label: node.gridName,
					children: node.children
				};
			},
			// 表单重置
			reset() {
				this.form = {
					materialId: null,
					materialCode: null,
					materialName: null,
					materialStatus: null,
					specifications: null,
					sortId: null,
					warehouseId: null,
					cabinetId: null,
					gridId: null,
					unitId: null,
					providerId: null,
					materialCategory: null,
					purchaseDate: null,
					inDate: null,
					preRepairDate: null,
					repairCycle: null,
					serviceLife: null,
					rfidCode: null,
					singleWeight: null,
					totalWeight: null,
					sparePartType: null,
					remark: null,
					delFlag: null,
					createBy: null,
					createTime: null,
					updateBy: null,
					updateTime: null
				};
				this.resetForm("form");
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.resetForm("queryForm");
				this.handleQuery();
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map(item => item.materialId)
				this.single = selection.length !== 1
				this.multiple = !selection.length
			},
			//根据库房展示柜架
			changeWarehouse() {
				this.queryCabinetParams.warehouseId = this.form.warehouseId;
				this.form.cabinetId = null;
				this.form.gridId = null;
				listCabinetOptions(this.queryCabinetParams).then(response => {
					this.cabinetOptions = response.data;
				});
			},
			//根据柜架展示层格
			changeCabinet() {
				this.queryGridParams.cabinetId = this.form.cabinetId;
				this.form.gridId = null;
				listBasGridOptions(this.queryGridParams).then(response => {
					this.gridOptions = this.handleTree(response.data, "gridId");
				});
			},
			/** 新增按钮操作 */
			handleAdd() {
				this.reset();

				this.cabinetOptions = [];

				this.gridOptions = [];

				listWarehouseOptions().then(response => {
					this.warehouseOptions = response.data;
				});
				listSortOptions().then(response => {
					this.sortOptions = this.handleTree(response.data, "sortId");
				});
				listProviderOptions().then(response => {
					this.providerOptions = response.data;
				});
				listUnitOptions().then(response => {
					this.unitOptions = response.data;
				});
				this.open = true;
				this.title = "添加工器具";
			},
			/** 修改按钮操作 */
			handleUpdate(row) {
				this.reset();
				listWarehouseOptions().then(response => {
					this.warehouseOptions = response.data;
				});
				listSortOptions().then(response => {
					this.sortOptions = this.handleTree(response.data, "sortId");
				});
				listProviderOptions().then(response => {
					this.providerOptions = response.data;
				});
				listUnitOptions().then(response => {
					this.unitOptions = response.data;
				});

				const materialId = row.materialId || this.ids
				getElecMaterial(materialId).then(response => {
					this.form = response.data;
					this.open = true;
					this.title = "修改工器具";
					this.queryCabinetParams.warehouseId = this.form.warehouseId;
					listCabinetOptions(this.queryCabinetParams).then(response => {
						this.cabinetOptions = response.data;
					});
					this.queryGridParams.cabinetId = this.form.cabinetId;
					listBasGridOptions(this.queryGridParams).then(response => {
						this.gridOptions = this.handleTree(response.data, "gridId");
					});
				});
			},
			/** 提交按钮 */
			submitForm() {
				this.$refs["form"].validate(valid => {
					if (valid) {
						if (this.form.materialId != null) {
							updateElecMaterial(this.form).then(response => {
								this.$modal.msgSuccess("修改成功");
								this.open = false;
								this.getList();
							});
						} else {
							this.form.materialCategory = '2';
							addElecMaterial(this.form).then(response => {
								this.$modal.msgSuccess("新增成功");
								this.open = false;
								this.getList();
							});
						}
					}
				});
			},
			/** 删除按钮操作 */
			handleDelete(row) {
				const materialIds = row.materialId || this.ids;
				this.$modal.confirm('是否确认删除工器具编号为"' + materialIds + '"的数据项？').then(function() {
					return delElecMaterial(materialIds);
				}).then(() => {
					this.getList();
					this.$modal.msgSuccess("删除成功");
				}).catch(() => {});
			},
			/** 导出按钮操作 */
			handleExport() {
				this.download('elec/elecMaterial/export', {
					...this.queryParams
				}, `工器具信息_${new Date().getTime()}.xlsx`)
			},
			/** 导入按钮操作 */
			handleImport() {
				this.upload.title = "工器具导入";
				this.upload.open = true;
			},
			/** 下载模板操作 */
			importTemplate() {
				this.download('elec/elecMaterial/importTemplate', {}, `工器具导入模板_${new Date().getTime()}.xlsx`)
			},
			// 文件上传中处理
			handleFileUploadProgress(event, file, fileList) {
				this.upload.isUploading = true;
			},
			// 文件上传成功处理
			handleFileSuccess(response, file, fileList) {
				this.upload.open = false;
				this.upload.isUploading = false;
				this.$refs.upload.clearFiles();
				this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg +
					"</div>", "导入结果", {
						dangerouslyUseHTMLString: true
					});
				this.getList();
			},
			// 提交上传文件
			submitFileForm() {
				this.$refs.upload.submit();
			}
		}
	};
</script>
